<script lang="ts" setup>
import { computed } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';

import {
  Card,
  CardGrid,
  InputNumber,
  message,
  QRCode,
  Segmented,
  Select,
} from 'ant-design-vue';

import {
  getMerchantsListUser,
  postFindOrder,
  postPayCheckstand,
} from '#/api/plugin/pay';

defineOptions({
  name: 'PluginPayAdminIndexcheckstand',
});

const payPlatform = ref([
  {
    value: 'wechat',
    payload: {
      title: '微信支付',
    },
  },
  {
    value: 'alipay',
    payload: {
      title: '支付宝支付',
    },
  },
  {
    value: 'unipay',
    payload: {
      title: '银联支付',
    },
  },
]);
const paytype = ref('wechat');
const payTypeList = computed(() => {
  const payTypes = [
    {
      method: 'web',
      mode: ['alipay', 'unipay'],
      icon: '',
      title: '电脑支付',
      intro: '刷卡支付',
    },
    {
      method: 'mp',
      mode: ['wechat'],
      icon: '',
      title: '公众号支付',
      intro: '',
    },
    {
      method: 'h5',
      mode: ['wechat', 'alipay', 'unipay'],
      icon: '',
      title: 'H5支付',
      intro: '',
    },
    {
      method: 'app',
      mode: ['wechat', 'alipay'],
      icon: '',
      title: 'APP 支付',
      intro: '',
    },
    {
      method: 'mini',
      mode: ['wechat', 'alipay'],
      icon: '',
      title: '小程序支付',
      intro: '',
    },
    {
      method: 'pos',
      mode: ['wechat', 'alipay', 'unipay'],
      icon: '',
      title: '刷卡支付',
      intro: '',
    },
    {
      method: 'scan',
      mode: ['wechat', 'alipay', 'unipay'],
      icon: '',
      title: '扫码支付',
      intro: '',
    },
    {
      method: 'transfer',
      mode: ['wechat', 'alipay'],
      icon: '',
      title: '账户转账',
      intro: '',
    },
  ];
  return payTypes.filter((item) => item.mode.includes(paytype.value));
});
const merchantId = ref();
const merchants = ref([]);
const amount = ref(0);
const qrcodeText = ref('');
const timer = ref<any>(null);
const num = ref(0);
const qrcodeStatus = ref<
  'active' | 'expired' | 'loading' | 'scanned' | undefined
>('active');

const [PayModal, PayModalApi] = useVbenModal({
  onBeforeClose() {
    qrcodeText.value = '';
    amount.value = 0;
    num.value = 0;
    if (timer.value) {
      clearInterval(timer.value);
    }
  },
  onConfirm: async () => {
    PayModalApi.close();
  },
});
onMounted(async () => {
  const {
    data: { list },
  } = await getMerchantsListUser();
  merchants.value = list;
});

const handleFindOrder = async (outTradeNo: string) => {
  const { data } = await postFindOrder({ out_trade_no: outTradeNo });
  if (num.value >= 180) {
    qrcodeStatus.value = 'expired';
  }
  if (data && data.status === 1) {
    message.success('支付成功');
    PayModalApi.close();
  }
};

const toPay = async (method: string, title: string) => {
  if (amount.value <= 0) {
    message.info('金额不能为0');
    return;
  }
  if (method !== 'scan') {
    message.info('此方式不支持扫码支付');
    return;
  }
  const formData = {
    paytype: paytype.value,
    channel: method,
    amount: amount.value,
    goods_id: 0,
    merchant_id: merchantId.value,
    /** app: 'portal',
    module: 'article',
    more: {
      id: 4,
    },*/
  };
  PayModalApi.setState({
    title: `${paytype.value} - ${title}`,
  });

  const {
    data: { result, qr_code },
  } = await postPayCheckstand(formData);
  if (result?.code === 0) {
    message.error(result.msg);
    return;
  }

  qrcodeText.value = qr_code;
  const outTradeNo = result.out_trade_no;
  if (!outTradeNo) {
    return;
  }
  // 如果是扫码支付则进行轮询
  if (method === 'scan') {
    timer.value = setInterval(() => {
      handleFindOrder(outTradeNo);
      num.value++;
    }, 1000);
  }

  PayModalApi.open();
};
</script>

<template>
  <Page auto-content-height>
    <PayModal class="w-[600px] text-center">
      <div class="flex flex-nowrap justify-center text-center">
        <QRCode
          :status="qrcodeStatus"
          :value="qrcodeText"
          class="size-16"
          @refresh="() => console.log('refresh')"
        />
      </div>
    </PayModal>

    <Card :bordered="false">
      <template #title>
        <span class="mr-6">支付平台</span>
        <Segmented v-model:value="paytype" :options="payPlatform">
          <template #label="{ payload }">
            <div style="padding: 4px">
              <div>{{ payload.title }}</div>
            </div>
          </template>
        </Segmented>
      </template>
      <Card :bordered="false" class="mb-5" title="收款商家">
        <Select
          v-model:value="merchantId"
          :field-names="{ label: 'name', value: 'id' }"
          :options="merchants"
          placeholder="选择商家"
          style="width: 300px"
        />
      </Card>
      <Card :bordered="false" class="mb-5" title="收款金额">
        <InputNumber
          v-model:value="amount"
          :formatter="
            (value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
          "
          :parser="(value) => value.replace(/\$\s?|(,*)/g, '')"
          prefix="￥"
          style="width: 300px"
        />
      </Card>
      <Card title="支付方式">
        <CardGrid
          v-for="(item, index) in payTypeList"
          :key="index"
          class="cursor-pointer text-center"
          style="width: 16.6666%"
          @click="toPay(item.method, item.title)"
        >
          {{ item.title }}
        </CardGrid>
      </Card>
    </Card>
  </Page>
</template>
